<%@ page import="entity.Department"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
%>

<div class="callout callout-left">
	<span class="callout-title text-muted">部门管理</span><!-- &nbsp;<span class="glyphicon glyphicon-question-sign"></span> -->
	<button class="btn btn-primary" id="create_dept" data-toggle="modal" data-target="#myModal" style="margin-left: 35px;"><span class="glyphicon glyphicon-plus-sign">&nbsp;新建直属部门</span></button>
</div>
	
<div class="callout">
	<form class="form-inline" method="post" onsubmit="return false;">
		<div class="form-group">
			<label for="deptName_search">部门名称：</label>
			<input type="text" class="form-control" id="deptName_search" name="deptName_search" placeholder="搜索部门名称"  autocomplete="off" />
		</div>&nbsp;&nbsp;&nbsp;
		<a class="btn btn-primary" id="doSearch" href="javascript:;"><span class="glyphicon glyphicon-search">&nbsp;搜索</span></a>&nbsp;&nbsp;&nbsp;
		<!-- <button class="btn btn-info"><span class="glyphicon glyphicon-remove-circle">&nbsp;清除</span></button> -->
	</form>
</div>
	
<div class="callout callout-white">
  <div class="table-responsive">
	<table class="table table-hover">
		<thead>
			<tr>
				<th>编号</th>
				<th>部门名称</th>
				<th>创建日期</th>
				<th>动作</th>
			</tr>
		</thead>
		<tbody id="depts_content">
		</tbody>
	</table>
  </div>
</div>
	
<script>
require.config({
	urlArgs: 'v88',
	baseUrl: '<%=path %>/js',
	paths: {
		jquery: 'jquery-1.9.1.min',
		commmon: 'common',
		datetimepicker: 'bootstrap-datetimepicker.min'
	}
});

require(['jquery', 'common', 'datetimepicker'], function($, common) {

//开始工作空间
var workspace = function() {

	var domKey;
	var dataOpt;
	var departments;

	var init = function() {
		domKey = common.commData.domKey;
		dataOpt = common.dataOpt;

		_initDeptsTable();// ->编辑、->删除模态框
		_createDept();// ->新建部门模态框
		_searchDept();
	}

	// 分页功能
	var pageNav = function(htmlArr) {
		var opt = {
			htmlArr: htmlArr,
			content: $("#depts_content"),
		}
		common.pageNav(opt, function() {
			deleteDept();
			editDept();
		});
	}

	// 初始化所有部门信息
	var _initDeptsTable = function() {
		departments = common.ajaxLoadData(dataOpt.departmentOpt);
		dataOpt.departmentOpt.data = {}
		
		var template = "<tr><th scope='row'>#row#</th>" +
			"<td>#deptName#</td>" +
			"<td>#createDate#</td>" +
			"<td>" +
			"<a href='#myModal' class='editDept' data-toggle='modal' data-deptname='#deptName#'><span class='glyphicon glyphicon-edit text-primary'>编辑</span></a>" +
			"&nbsp;&nbsp;<a href='#myModal' class='delDept' data-toggle='modal' data-deptname='#deptName#'><span class='glyphicon glyphicon-remove text-primary'>删除</span></a>" +
			"</td></tr>";

		var row = 0;
		var htmlArr = [];
		var html = "";
		var thisT = "";
		for(var i = 0, n = departments.length; i < n; i++ ) {
			thisT = template;
			thisT = thisT.replace(/#row#/g, ++row).replace(/#deptName#/g, departments[i]["deptName"]).replace(/#createDate#/g, departments[i]["createDate"]);
			html += thisT;
			if((row != 0) && (row % common.commData.pageNum === 0)) {
				htmlArr.push(html);
				html = "";
			}
		}
		$("#depts_content").html(html);

		if("" !== html) {
				htmlArr.push(html);// 插入不满pageNum的几条数据
		}

		pageNav(htmlArr);
	}

	// 新建部门：ajax请求形式
	var _createDept = function() {// 点击新建部门按钮
		var modalBodyTemplate = "<form class='form-horizontal'>" +
			"<div class='form-group'>" +
			"<label for='deptName' class='col-sm-4 control-label'>部门名称</label>" +
			"<div class='col-sm-8'>" +
			"<input type='text' class='form-control' id='deptName' name='deptName' placeholder='部门名称' autocomplete='off' />" +
			"</div></div>" +
			"</from>";

		$("#create_dept").click(function() {
			common.cleanModal();
			domKey.modal.find(".modal-dialog").addClass("modal-sm");
			domKey.modalLabel.html("新建部门");
			domKey.modalBody.html(modalBodyTemplate);

			domKey.modalAct.html("新建")
			.on("click", function() {
				common.disable($(this));// 提交请求则禁掉按钮
				// 获取填写的信息
				var data = {
					"deptName": $("#deptName").val()
				}
				if(data["deptName"].length > 0 && data["createDate"].length > 0) {
					$.ajax({
						url: "<%=path %>/servlet/dept/CreateDeptServlet",
						type: "post",
						data: data,
						dataType: "json",
						async: false,
						success: function(json) {
							if("1" === json["retCode"]) {

							} else {
								alert(json["desc"]);
							}
						},
						error: function(XMLHttpRequest, textStatus, errorThrown) {
							alert("CreateDeptServlet:" + XMLHttpRequest.status + ":" + XMLHttpRequest.readyState+ ":" + textStatus);
						},
						complete: function() {
							domKey.modal.find(".close").click();
							_initDeptsTable();// 刷新表格
						}
					});
				} else {
					alert("请填写所有信息");
					common.enable(domKey.modalAct);
				}
			});
		});
	}
	
	// 删除部门：ajax请求形式
	var deleteDept = function() {
		var modalBodyTemplate = "<span class='glyphicon glyphicon-info-sign' style='color:#FF8A00;font-size:26px;margin-right:15px;top:7px;'></span>确认删除#name#？";
		$(".delDept").each(function() {
			var deptName = $(this).data("deptname");
			$(this).on("click", function() {
				common.cleanModal();
				domKey.modal.find(".modal-dialog").addClass("modal-sm");
				var thisTemplate = modalBodyTemplate;
				thisTemplate = thisTemplate.replace(/#name#/g, deptName);
				domKey.modalLabel.html("删除直属部门");
				domKey.modalBody.html(thisTemplate);
				domKey.modalAct.html("确认")
				.on("click", function() {
					common.disable($(this));// 提交请求则禁掉按钮
					$.ajax({
						url: "<%=path %>/servlet/dept/DelDeptServlet",
						type: "post",
						data: {"deptName": deptName},
						dataType: "json",
						async: false,
						success: function(data) {
							if("1" === data["retCode"]) {

							} else {
								alert(data["desc"]);
							}
						},
						error: function(XMLHttpRequest, textStatus, errorThrown) {
							alert("服务器错误:" + XMLHttpRequest.status + ":" + XMLHttpRequest.readyState+ ":" + textStatus);
						},
						complete: function() {
							domKey.modal.find(".close").click();
							_initDeptsTable();// 刷新表格
						}
					});
				});
			});
		});
	}
	
	// 编辑部门：ajax请求形式
	var editDept = function() {
		var modalBodyTemplate = "<form class='form-horizontal'>" +
			"<div class='form-group'>" +
			"<label for='deptName' class='col-sm-3 control-label'>名称</label>" +
			"<div class='col-sm-9'>" +
			"<input type='text' class='form-control' id='deptName' name='deptName' placeholder='名称' autocomplete='off' />" +
			"</div></div></form>";

		$(".editDept").each(function() {
			var oldName = $(this).data("deptname");
			var newName = oldName;
			$(this).on("click", function() {
				common.cleanModal();
				common.disable(domKey.modalAct);
				domKey.modal.find(".modal-dialog").addClass("modal-sm");
				domKey.modalLabel.html("修改直属部门");
				domKey.modalBody.html(modalBodyTemplate);

				$("#deptName").val(oldName)
				.bind("input porpertychange", function() {
					newName = $(this).val();
					if(oldName == newName) {
						common.disable(domKey.modalAct);
					} else {
						common.enable(domKey.modalAct);
					}
				});
				
				domKey.modalAct.html("确认")
				.on("click", function() {
					common.disable($(this));// 提交请求则禁掉按钮
					$.ajax({
						url: "<%=path %>/servlet/dept/EditDeptServlet",
						type: "post",
						data: {"oldName":oldName,"newName":newName},
						dataType: "json",
						async: false,
						success: function(json) {
							if("1" === json["retCode"]) {
								if( "" !== json["change"]) {
									$("#curDept").html(json["change"]);
								}
							} else {
								alert(json["desc"]);
							}
						},
						error: function(XMLHttpRequest, textStatus, errorThrown) {
							alert("服务器错误:" + XMLHttpRequest.status + ":" + XMLHttpRequest.readyState+ ":" + textStatus);
						},
						complete: function() {
							domKey.modal.find(".close").click();
							_initDeptsTable();// 刷新表格
						}
					});
				});
			});
		});
	}
	
	var _searchDept = function() {
		$("#doSearch").click(function() {
			dataOpt.departmentOpt.data = {
				"deptName": encodeURI(encodeURI($("#deptName_search").val()))
			}
			_initDeptsTable();
		});
	}
	
	return {
		init: init
	}
}();

$(function() { workspace.init(); });

});

requirejs.onError = function (err) {  
	console.error(err);
	if (err.requireType === 'timeout') {
			console.error('modules: ' + err.requireModules);
	}
	throw err;
}
</script>
